package com.wanmait.mpdemo.controller;


import com.wanmait.mpdemo.entity.Question;
import com.wanmait.mpdemo.service.QuestionService;
import com.wanmait.mpdemo.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-01-14
 */
@RestController
@RequestMapping("/manage/question")
@CrossOrigin
public class QuestionController {
    @Resource
    private QuestionService questionService;


    @GetMapping("list")
    public Result list(String title){
        return Result.success(questionService.listByTitle(title));
    }

    @PostMapping("insert")
    public Result insert(Question question, MultipartFile picFile, HttpServletRequest request){

        System.out.println(question);

        if(!picFile.isEmpty()){
            //判断大小
            if(picFile.getSize()>1024*1024*2){
                return Result.error("图片上传大小不能超过2M");
            }
            //获得扩展名
            String ext = FilenameUtils.getExtension(picFile.getOriginalFilename());
            if(!",jpg,jpeg,gif,webp,png,".contains(","+ext.toLowerCase()+",")){
                return Result.error("只能上传图片jpg,jpeg,gif,webp,png");
            }
            try {
                //获得物理路径
                String path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadImages";
                //String path = "D:\\uploadImages";
                String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
                //保存图片
                picFile.transferTo(new File(path,fileName));
                question.setPic(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("上传图片出错");
            }

        }
        questionService.save(question);
        return Result.success("添加问题成功");
    }
}
